﻿package taurus.client;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 网络管理对象
 * @author daixiwei	daixiwei15@126.com
 *
 */
public class NetManager {

	private static List<TaurusClient>			_clientList		= new ArrayList<TaurusClient>();
	private static Map<Integer, TaurusClient>	_clientMap		= new HashMap<Integer, TaurusClient>();

	/**
	 * 网络超时时间
	 */
	public static int						TIMEOUT_TIME	= 10;
	/**
	 * 网络版本号
	 */
    public static int 						VERSION			= 10;
	public static boolean 					debug_print 	= true;

	static void addNetClient(TaurusClient net) {
		if (net == null) {
			throw new RuntimeException("TaurusClient is null, it can't be added.");
		}
		if (_clientMap.containsKey(net.getId())) {
			throw new RuntimeException("A client with id: " + net.getId() + " already exists! Controller can't be added: " + net);
		}
		synchronized (_clientList) {
			_clientMap.put(net.getId(), net);
			_clientList.add(net);
		}

	}

	/**
	 * The process events
	 */
	public static void processEvents() {
		for (int i = 0; i < _clientList.size(); ++i) {
			TaurusClient nc = _clientList.get(i);
			if (nc._kill){
				synchronized (_clientList) {
	                _clientMap.remove(nc.getId());
	                _clientList.remove(nc);
				}
                i--;
                continue;
            }else{
            	nc.processEvent();
            }
		}

	}

	/**
	 * 返回指定的NetClient
	 * @param id
	 * @return
	 */
	public static TaurusClient getNetClient(int id) {
		for (int i = 0; i < _clientList.size(); ++i) {
			TaurusClient nc = _clientList.get(i);
			if (nc.getId() == id)
				return nc;
		}
		return null;
	}

	/**
	 * 断开指定连接
	 * @param id
	 */
	public static void killConnection(int id) {
		for (int i = 0; i < _clientList.size(); ++i) {
			TaurusClient nc = _clientList.get(i);
			if (nc.getId() == id) {
				nc.killConnection();
				synchronized (_clientList) {
					_clientMap.remove(id);
					_clientList.remove(nc);
				}
				break;
			}
		}
	}

	/**
	 * 断开所有连接
	 */
	public static void killAllConnection() {
		synchronized (_clientList) {
			for (TaurusClient nc : _clientList) {
				nc.killConnection();
			}
			_clientList.clear();
			_clientMap.clear();
		}

	}
}
